using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CrmSdk;

public partial class ContactPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    public void crmGrid_QueryDataSource(object sender, QueryDataSourceEventArgs args)
    {
		object dataSource = null;
		
		try
		{
			dataSource = GetDataSource(args);
		}
		catch(Exception ex)
		{
			dataSource = GetDummyDataTable(args);
		}
		
        this.crmGrid.DataSource = dataSource;
        this.crmGrid.DataBind();
        
        if (string.IsNullOrEmpty(args.SortExpression))
        {
            args.SortExpression = "fullname";
        }
    }

	object GetDataSource(QueryDataSourceEventArgs args)
	{
		CrmSdk.CrmAuthenticationToken token = new CrmSdk.CrmAuthenticationToken();
        token.OrganizationName = ConfigurationManager.AppSettings["OrgName"];

		CrmSdk.CrmService crmService = new CrmSdk.CrmService();
		crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
		crmService.CrmAuthenticationTokenValue = token;
		crmService.Url = ConfigurationManager.AppSettings["CrmSdk.CrmServiceWsdl"];

		PagingInfo pageInfo = new PagingInfo();
		pageInfo.Count = 50;
		pageInfo.PageNumber = args.PageNumber;
		pageInfo.PagingCookie = args.PagingCookie;

		RetrieveMultipleRequest request = new RetrieveMultipleRequest();

		QueryExpression query = new QueryExpression();

		if (args.SortExpression == string.Empty)
		{
			args.SortExpression = "fullname";
			args.SortDirection = SortDirection.Ascending;
		}

		OrderExpression order = new OrderExpression();
		order.AttributeName = args.SortExpression;
		order.OrderType = args.SortDirection == SortDirection.Ascending ? OrderType.Ascending : OrderType.Descending;

		query.Orders = new OrderExpression[] { order };

		query.EntityName = EntityName.contact.ToString();
		query.ColumnSet = new AllColumns();
		query.PageInfo = pageInfo;

		request.Query = query;
		RetrieveMultipleResponse response = crmService.Execute(request) as RetrieveMultipleResponse;
		args.HasMorePages = response.BusinessEntityCollection.MoreRecords;
		args.PagingCookie = response.BusinessEntityCollection.PagingCookie;

		return response.BusinessEntityCollection.BusinessEntities;
	}

	DataTable GetDummyDataTable(QueryDataSourceEventArgs args)
	{
		DataTable table = new DataTable();
		table.Columns.Add(new DataColumn("fullname"));
		table.Columns.Add(new DataColumn("emailaddress1"));
		table.Columns.Add(new DataColumn("telephone1"));

		for (int I = 0; I < 50; I++)
		{
			object[] values = new object[table.Columns.Count];
			for (int j = 0; j < table.Columns.Count; j++)
			{
				values[j] = table.Columns[j].ColumnName+"("+I+","+j+")";
			}
			table.Rows.Add(values);
		}

		return table;
	}
}
